package com.cskaoyan.filter;

import com.cskaoyan.admin.servlet.AdminServlet;
import com.cskaoyan.common.bean.vo.BaseRespVo;
import com.cskaoyan.util.JsonUtil;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 过滤器
 *
 * @author 侯嘉
 * @since 2024/04/09 22:34
 */
@WebFilter("/*")
public class AuthFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {}

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 跨域处理
        corsDeal(servletResponse);
        // 设置请求的中文字符集，响应的字符集需要自己设置
        servletRequest.setCharacterEncoding("utf-8");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 登录判断
        if (isLoginUri(request) || isLogin(request)) {
            // 执行Servlet的service方法
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            JsonUtil.responseJson(response, BaseRespVo.msg("请先登录"));
        }

    }

    private boolean isLoginUri(HttpServletRequest request) {
        String contextPath = request.getContextPath();
        String totalUri = request.getRequestURI();
        String uri = totalUri.replace(contextPath, "");
        return "/admin/auth/login".equals(uri);
    }

    private boolean isLogin(HttpServletRequest request) {
        Object admin = request.getSession().getAttribute(AdminServlet.ADMIN_KEY);
        return admin != null;
    }

    /**
     * 跨域处理
     */
    private void corsDeal(ServletResponse servletResponse) {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setHeader("Access-Control-Allow-Origin", "http://localhost:8080");
        response.setHeader("Access-Control-Allow-Methods","POST,GET,OPTIONS,PUT,DELETE");
        response.setHeader("Access-Control-Allow-Headers","x-requested-with,Authorization,Content-Type,X-CskaoyanMarket-Admin-Token,X-CskaoyanMarket-Token");
        response.setHeader("Access-Control-Allow-Credentials","true");
    }

}
